import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import login from '../views/login.vue'
import index from '../views/index.vue'
import store from '@/store'
// import { component } from 'vue/types/umd'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: "/login",
    component: login,
    // 
  },
  {
    path: '/login',
    component: login,

  },
  {
    path: '/401',
    component: () => import('../views/401.vue'),

  },
  {
    path: '/home',
    component: HomeView,
    // redirect: "/index",
    children: [
      {
        path: '/index',
        component: index,
        meta: {
          title: "首页"
        }
      },
      {
        path: '/xgl',
        component: () => import('../views/xgl/xgl.vue'),
        meta: {
          permission: "1",
          title: "系管理"
        }
      },
      {
        path: '/zygl',
        component: () => import('../views/zygl/zygl.vue'),
        meta: {
          permission: "2",
          title: "专业管理"
        }
      },
      {
        path: '/bjgl',
        component: () => import('../views/bjgl/bjgl.vue'),
        meta: {
          permission: "4",
          title: "班级管理"
        }
      },
      {
        path: '/xsgl',
        component: () => import('../views/xsgl/xsgl.vue'),
        meta: {
          permission: "8",
          title: "学生管理"
        }
      },
      {
        path: '/jsgl',
        component: () => import('../views/jsgl/jsgl.vue'),
        meta: {
          permission: "16",
          title: "教师管理"
        }
      },
      {
        path: '/kcgl',
        component: () => import('../views/kcgl/kcgl.vue'),
        meta: {
          permission: "32",
          title: "课程管理"
        }
      },
      {
        path: '/xkxg',
        component: () => import('../views/xkxg/xkxg.vue'),
        meta: {
          permission: "64",
          title: "选课修改"
        }
      },
      {
        path: '/glygl',
        component: () => import('../views/glygl/glygl.vue'),
        meta: {
          permission: "128",
          title: "管理员管理"
        }
      },
    ]
  },

]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})
// 路由守卫
// 1，是否登录了
// 2，是否有权限
router.beforeEach((to, from, next) => {
  //to 去哪个页面
  //from 来自那个页面
  //next 是个函数,放行

  //1.是否登录了

  console.log(store.state.user.info);
  //已经登录了
  if (store.state.user.info.loggedIn) {
    if(to.path=="/login"){
      //跳转到首页
      next("/index")
  }else{
    //不是登录页，放行
    //判断是否有权限
    //用户权限 store.state.user.info.group
    if(store.state.user.info.group.indexOf(to.meta.permission) !=-1|| !to.meta.permission){
       next()
    }else{
      //没有权限
      next("/401")
    }
  }
    
  }else{
    //没有登录
    if(to.path=="/login"){
      //登录页，放行
      next()
  }else{
    //不是登录页，去登录页
    next("/login")
  }
  }
})

export default router
